package com.liuyang.demo.scanpackage;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware {


    @Value("${spring.profiles.active:prod}")
    private String env;

    @Value("${dubbo.registry.address:}")
    protected String registryAddress;

    @Value("${dubbo.registries.hmsd.address:}")
    protected String registriesHmsdAddress;

    /**
     * Spring应用上下文环境
     */
    private static ApplicationContext applicationContext;

    /*

     * 实现了ApplicationContextAware 接口，必须实现该方法；

     *通过传递applicationContext参数初始化成员变量applicationContext

     */

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
        //if (EnvType.TEST.getActive().equals(env)) {
        if ("test".equals(env)) {
            if (StringUtils.isNotBlank(registryAddress)) {
                String zk = registryAddress.split(":")[0];
                InetAddress[] allByName = null;
                try {
                    allByName = InetAddress.getAllByName(zk);
                } catch (UnknownHostException e) {
                    log.error("ERROR", e);
                }
                log.info("ZK地址:{}, IP:{}", zk, allByName);
            }else{
                String zk = registriesHmsdAddress.split(":")[0];
                InetAddress[] allByName = null;
                try {
                    allByName = InetAddress.getAllByName(zk);
                } catch (UnknownHostException e) {
                    log.error("ERROR", e);
                }
                log.info("ZK地址:{}, IP:{}", zk, allByName);
            }
        }
    }


    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }


    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class clz) throws BeansException {
        return (T) applicationContext.getBean(clz);
    }

}